//
//  DashboardViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit
import SwiftDate
import SVProgressHUD
import HealthKit

class DashboardViewController: RViewController {

    /// 导航栏高度
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    /// 距离顶部距离 正常15 离线38
    @IBOutlet weak var marginTop: NSLayoutConstraint!
    /// 离线指示label
    @IBOutlet weak var offlineLabel: UILabel!
    /// 离线指示label高度
    @IBOutlet weak var offlineLabelHeight: NSLayoutConstraint!
    /// 标题
    @IBOutlet weak var titleLabel: UILabel!
    /// 电池
    @IBOutlet weak var baterryIcon: UIImageView!
    /// 上传
    @IBOutlet weak var uploadBtn: UIButton!
    /// 血氧
    @IBOutlet weak var SpO2View: UIView!
    var O2Circle = LXCircleAnimationView.init()
    @IBOutlet weak var currentSpo2: UILabel!
    /// 脉搏
    @IBOutlet weak var PulseRateView: UIView!
    @IBOutlet weak var currentHr: UILabel!
    var HRCircle = LXCircleAnimationView.init()
    /// 设备
    var deviceCom = VTBLEUtils.init()
    var timer: Timer?
    
    var dataArray = [RModel]()
    
    /// 读取设备历史数据的文件下标，不然不知道是否完成
    var currentIndex = 0
    /// 需要读取的文件名列表
    var shouldReadFileList = [String]()
    /// 当前页面是否活跃
    var isActive = true
    let healthStore = HKHealthStore()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationHeight.constant = 44 + getStatusBarHight()
        self.view.backgroundColor = hexColor("F9F9F9")
        self.SpO2View.layer.cornerRadius = 10
        self.PulseRateView.layer.cornerRadius = 10
        self.uploadBtn.setTitle(nil, for: .normal)
        
        // 血氧
        let width = 180
        self.O2Circle = LXCircleAnimationView.init(frame: CGRect(x: (Int(kScreenWidth) - 180 - 15 * 2) / 2, y: 52, width: width, height: width), gradientLayerColors: [hexColor("3367E1")!.cgColor, hexColor("5B88F5")!.cgColor])
        self.O2Circle.percent = 0
        self.SpO2View.addSubview(self.O2Circle)
        
        // 脉搏
        self.HRCircle = LXCircleAnimationView.init(frame: CGRect(x: (Int(kScreenWidth) - 180 - 15 * 2) / 2, y: 52, width: width, height: width), gradientLayerColors: [hexColor("FF2C20")!.cgColor, hexColor("FF9158")!.cgColor])
        self.HRCircle.percent = 0
        self.PulseRateView.addSubview(self.HRCircle)
        
        /// 设备是否离线
        self.setDeviceOffline(offline: false)
        
        self.titleLabel.text = RManager.manager.isBig ? "CMRing" : "CMRingS"
        
    }
    
    /// 上传按钮
    @IBAction func uploadBtnDidClicked(_ sender: Any) {
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 后台重回前台
        NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        // 前台到后台
        NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeBackForgeound), name: UIApplication.willResignActiveNotification, object: nil)
        // 上传图标
        NotificationCenter.default.addObserver(self, selector: #selector(uploadFinshFunction), name: NSNotification.Name.init(rawValue: UploadState), object: nil)
        
        RManager.manager.startOnlineUpload()
        
        self.uploadBtn.isHidden = true
        if RManager.manager.uploading == true {
            self.uploadBtn.isHidden = false
        }
       
        // 常亮
        UIApplication.shared.isIdleTimerDisabled = true
        
        self.startGetData()
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 常亮关闭
        UIApplication.shared.isIdleTimerDisabled = false
        
        NotificationCenter.default.removeObserver(self)
        
        /// 上传苹果健康
        HealthTool.uploadDataToAppleHealth(datas: self.dataArray)
        self.endGetData()
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
    }
    
    /// 开始获取数据
    func startGetData() {
        
        self.isActive = true
        /// 没有设备链接
        if RManager.manager.currentDevice == nil {
            self.O2Circle.percent = 0
            self.HRCircle.percent = 0
            self.currentHr.text = "—"
            self.currentSpo2.text = "—"
            return
        }
        VTO2Communicate.sharedInstance().delegate = self
        VTO2Communicate.sharedInstance().beginGetInfo()
    }
    
    /// 终止获取数据
    func endGetData() {
        
        self.isActive = false
        VTO2Communicate.sharedInstance().delegate = nil
        if let timer = self.timer {
            timer.fireDate = Date.distantFuture
        }
        
        if self.dataArray.count <= 3 {
            return
        }
        
        /// 存储数据  [时间戳：数据]  再把时间戳key存储起来，方便读取
        let cachePrefix = String(Int(Date().timeIntervalSince1970))
        
        
//        self.dataArray.append(RModel.init(fromeLocal: 1646287055))
//        self.dataArray.append(RModel.init(fromeLocal: 1646287056))
//        self.dataArray.append(RModel.init(fromeLocal: 1646287057))
//        self.dataArray.append(RModel.init(fromeLocal: 1646287058))
//        self.dataArray.append(RModel.init(fromeLocal: 1646287059))
//        let cachePrefix = "1646287059"
        
        
        CacheManager.manager.setValueForKey(cachePrefix, self.dataArray as NSCoding) {
            var historyData = CacheManager.manager.getValueForKey(HistoryData) as! Array<String>
            historyData.append(cachePrefix)
            CacheManager.manager.setValueForKey(HistoryData, historyData as NSCoding)
            self.dataArray.removeAll()
        }
        
        // 通知history刷新
//        NotificationCenter.default.post(name: NSNotification.Name(rawValue: HistoryShouldReload), object: nil)
    }
    
    @objc func appDidBecomeActive() {
        self.startGetData()
    }
    
    @objc func appDidBecomeBackForgeound() {
        self.endGetData()
    }
    
    // 上传完成，隐藏实时上传图标
    @objc func uploadFinshFunction() {
        self.uploadBtn.isHidden = !RManager.manager.uploading
    }
    
    /// 读取蓝牙数据
    @objc func readRealTimeData() {
        VTO2Communicate.sharedInstance().beginGetRealData()
    }

}

extension DashboardViewController: VTO2CommunicateDelegate {
    
    /// 获取数据
    func realDataCallBack(with realData: Data?) {
        if realData == nil {
            return
        }
        let rObj = VTO2Parser.parseO2RealObject(with: realData ?? Data.init())
        
        if rObj.leadState == 1, rObj.spo2 != 0 {
            
            /// 设备是否离线
            self.setDeviceOffline(offline: false)
            
            // 读取并显示数据
            let o2Percent = CGFloat((Float(rObj.spo2) - 70) / 30.0 * 100)
            self.O2Circle.percent = o2Percent
            self.currentSpo2.text = String(rObj.spo2) + "%"
            
            let hrPercent = CGFloat((Float(rObj.hr) - 30) / 220.0 * 100)
            self.HRCircle.percent = hrPercent
            self.currentHr.text = String(rObj.hr)
            
            if Int(rObj.battery) > 50 {
                self.baterryIcon.image = UIImage.init(named: "baterry100")
            }
            if Int(rObj.battery) <= 50, Int(rObj.battery) > 20 {
                self.baterryIcon.image = UIImage.init(named: "baterry50")?.maskImageWithColor(color: hexColor("F2AD48")!)
            }
            if Int(rObj.battery) <= 20 {
                self.baterryIcon.image = UIImage.init(named: "baterry20")
            }
            
            // 添加数据到缓存
            let model = RModel.init(fromVTObjectr: rObj)
            RManager.manager.onlineUploadData.append(model)
            self.dataArray.append(model)
            
        }else {
            /// 设备是否离线
            if self.dataArray.count != 0 {
                self.setDeviceOffline(offline: true)
            }
            self.O2Circle.percent = 0
            self.HRCircle.percent = 0
            self.currentHr.text = "—"
            self.currentSpo2.text = "—"
        }
    }
    
    /// 设备是否离线
    func setDeviceOffline(offline: Bool) {
        self.offlineLabelHeight.constant = offline ? 24 : 0
        self.marginTop.constant = offline ? 38 : 15
    }
    
    /// 读取设备数据
    func getInfoWithResultData(_ infoData: Data?) {
        SVProgressHUD.show()
        if let infoData = infoData {
            let info = VTO2Parser.parseO2Info(with: infoData)
            RManager.manager.info = info
            var fileList = info.fileList.components(separatedBy: ",")
            fileList.removeLast()
            
            // 需要读取的文件列表
            shouldReadFileList = [String]()
            for fileName in fileList {
                // 看历史同步数据中是否已同步过数据
                if let historyFile = CacheManager.manager.getValueForKey(HistoryOfRing) as? [String] {
                    // 没有则添加至需要读取的
                    if historyFile.contains(fileName) == false {
                        shouldReadFileList.append(fileName)
                    }
                }
            }
            
            if shouldReadFileList.count > 0 {
                self.getFileDataWithIndex(index: 0)
            }else {
                self.initTimer()
            }
            
        }else {
            // 读取设备信息，会走两遍空，才有数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                if self.shouldReadFileList.count == 0 {
                    self.initTimer()
                }
            }
        }
    }
    
    /// 并行，一个个的读取设备
    func getFileDataWithIndex(index: Int) {
        // 读取设备中的历史数据
        VTO2Communicate.sharedInstance().beginReadFile(withFileName: shouldReadFileList[index])
    }
    
    /// 读取文件数据
    func readComplete(withData fileData: VTFileToRead) {
        // 如果是读取成功
        if fileData.enLoadResult == VTFileLoadResultSuccess {
            let obj = VTO2Parser.parseO2Object(with: fileData.fileData as Data)
            let array: [VTO2WaveObject] = VTO2Parser.parseO2WaveObjectArray(withWave: obj.waveData)
            
            /// 存储数据  [时间戳：数据]  再把时间戳key存储起来，方便读取
            let time = "\(obj.year)-\(obj.month)-\(obj.day) \(obj.hour):\(obj.minute):\(obj.second)"
            let cachePrefix = String(Int(timeStrChangeToTimeInterval(timeStr: time, dateFormat: "yyyy-MM-dd HH:mm:ss")))
            
            var fileRModel = [RModel]()
            // 间隔
            let spacing = Int(obj.recordTime) / array.count
            for (i, waveObj) in array.enumerated() {
                if waveObj.spo2 < 80 || waveObj.spo2 > 100 {
                    continue
                }
                // 转为model
                fileRModel.append(RModel.init(waveObj: waveObj, time: Int(cachePrefix)! + spacing * i))
            }
            
            // 加入到需要上传的列表中
            RManager.manager.needUpdateData.append(contentsOf: fileRModel)
            
            // 存[Model]所有数据
            CacheManager.manager.setValueForKey(cachePrefix, fileRModel as NSCoding) {
                var historyData = CacheManager.manager.getValueForKey(HistoryData) as! Array<String>
                historyData.append(cachePrefix)
                // 排序到合适的时间
                historyData.sort()
                // 存标题
                CacheManager.manager.setValueForKey(HistoryData, historyData as NSCoding) {
                    
                    // 更新已读取的设备文件
                    var historyFileList = CacheManager.manager.getValueForKey(HistoryOfRing) as! Array<String>
                    historyFileList.append(self.shouldReadFileList[self.currentIndex])
                    CacheManager.manager.setValueForKey(HistoryOfRing, historyFileList as NSCoding) {
                        self.continueRead()
                    }
                    
                }
            }
            
            // 通知history刷新
//            NotificationCenter.default.post(name: NSNotification.Name(rawValue: HistoryShouldReload), object: nil)
            
        }else {
            continueRead()
        }
        
    }
    
    // 继续读取
    func continueRead() {
        self.currentIndex += 1
        if self.currentIndex == shouldReadFileList.count {
            // 全部读取完成
            SVProgressHUD.dismiss()
            currentIndex = 0
            shouldReadFileList.removeAll()
            DispatchQueue.main.async {
                self.initTimer()
            }
            
            // 上传历史数据
            if CacheManager.manager.containsObject(forKey: HistoryUploadConfig), let config = CacheManager.manager.getValueForKey(HistoryUploadConfig) as? UploadConfig {
                if config.auto == false {
                    return
                }
                self.uploadBtn.isHidden = false
                RManager.manager.uploadHistoryListToCloud(isHistory: true)
            }
            
        }else {
            // 继续读取
            getFileDataWithIndex(index: self.currentIndex)
        }
    }
    
    func initTimer() {
        SVProgressHUD.dismiss()
        if self.isActive == false {
            return
        }
        if let timer = timer {
            if timer.fireDate == Date.distantPast {
                return
            }
            timer.fireDate = Date.distantPast
        }else {
            self.timer = Timer.scheduledTimer(timeInterval: TimeInterval.init(ReadRate), target: self, selector: #selector(self.readRealTimeData), userInfo: nil, repeats: true)
            self.timer!.fireDate = Date.distantPast
        }
    }
    
}
